%% loading from a master file, filter out cases of interest

% choose cells from a particular base folder
% choose cells for a particular amplitude 
clearvars -except master

if (isa(master,'table'))
    master = table2struct(master);
end

% to filter by base directory
rows = []; 
row_ind = 1; 
for i=1:length(master)
    file = master(i).dir;
    file = strsplit(file,"/");
    base = file(length(file)); 
    if contains(base, "efast1")
        rows(row_ind) = i;
        row_ind = row_ind +1; 
    end
end 

%to filter by some other feature
rows =  [];
row_ind = 1;
for i=1:length(master)
    fil = master(i).amp;
    if (fil==0.2)
        rows(row_ind) = i;
        row_ind = row_ind +1; 
    end
end 

% to filter by version
rows = []; 
row_ind = 1; 
for i=1:length(master)
    note = master(i).notes;
    if (contains(note, "amp_freq_rest"))
        rows(row_ind) = i;
        row_ind = row_ind +1; 
    end
end 


% to filter by multiple things 
rows = []; 
row_ind = 1; 
for i=1:length(master)
    note = master(i).notes;
    amp = master(i).amp; 
      file = master(i).dir;
    file = strsplit(file,"/");
    base = file(length(file)-1); 
    if (contains(note, "onecell randpot")&& amp==0.1 && base=="onecell")
        rows(row_ind) = i;
        row_ind = row_ind +1; 
    end
end 
% to not reset row ind 
for i=1:length(master)
    note = master(i).notes;
    amp = master(i).amp; 
    if (contains(note, "onecell randpot")&& amp==0.066667)
        rows(row_ind) = i;
        row_ind = row_ind +1; 
    end
end 

% calculate the things that we want to calculate 
% filter out the cell strains of interest

for i=1:length(rows)
    row  = struct2cell(master(rows(i)));
    strains_all(:,i)=cat(2,row{20:length(row)})';
end

fifties = zeros(1,length(rows));
%inverted = zeros(time, length(cells));
%mins_all = []; %size is not certain, depends on peaks 
slopes = zeros(1, length(rows)); 
inds_min = zeros(2,length(rows)); 
halfxy = zeros(2,length(rows)); 

for i=1:length(rows)
   strains = strains_all(:,i); 
   fif = drop(strains);
   [~,lo1] = envelope(strains, 5, 'peak');
    vals = find(lo1==strains);
    up_ind = find(vals>=(fif));
    low_ind = find(vals<(fif));
      if isempty(low_ind)
            ind_low = 1;
      else
            ind_low = vals(low_ind(length(low_ind)));
      end
      if isempty(up_ind)
          ind_high=50; 
      else
          ind_high = vals(up_ind(1));
      end
   
   inds_min(:,i) = [ind_low; ind_high]; 
   slopes(i) = (strains(inds_min(2,i))-strains(inds_min(1,i)))/(inds_min(2,i)-inds_min(1,i)); 
   halfxy(1,i) = ( (-0.5-strains(inds_min(1,i)))/slopes(i) ) + inds_min(1,i); %xvalue of half time
   fifties(i) = halfxy(1,i);
   halfxy(2,i) = slopes(i)*(halfxy(1,i)-inds_min(1,i))+strains(inds_min(1,i)); %y value of half time
end

csvwrite('half1.csv',halfxy(1,:))
csvwrite('slopes1.csv', slopes)
